package com.hc.security;

import com.hc.bean.Result;
import com.hc.bean.ResultUtil;
import com.hc.utils.JsonUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限不足处理器，用来处理AccessDeniedException异常
 *
 * @author 梁云亮
 */
@Component
public class TokenAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex) throws IOException{

        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        ServletOutputStream outputStream = response.getOutputStream();

        Result result = ResultUtil.fail(400, "权限不足，请联系管理员！！！", ex.getMessage());

        outputStream.write(JsonUtil.obj2String(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();

    }
}